﻿using System;
using System.Xml;
using System.Text.RegularExpressions;
namespace V5_EaspLibs.Core {
    /// <summary>
    /// XML 的摘要说明。
    /// </summary>
    public class WebConfigHelper {
        #region 保存Web.config
        /// <summary>
        /// 保存Web.config
        /// </summary>
        /// <param name="strKeyName">节点名</param>
        /// <param name="strKeyValue">要保存的值</param>
        /// <param name="strWhich">哪个配置文件</param>
        public static void SaveSetting(string strKeyName, string strKeyValue, string strWhich) {
            //创建XML文档实例
            System.Xml.XmlDocument XMLWebSetting = new System.Xml.XmlDocument();

            //打开XML文档
            XMLWebSetting.Load(System.Web.HttpContext.Current.Server.MapPath("~/" + strWhich + ""));

            //查找节点所在位置
            System.Xml.XmlNodeList XmlNodeList = XMLWebSetting.SelectSingleNode("//appSettings").ChildNodes;
            try {
                foreach (System.Xml.XmlNode xn in XmlNodeList) {
                    System.Xml.XmlElement xe = ((System.Xml.XmlElement)(xn));
                    if (xe.Attributes["key"].InnerText == strKeyName) {
                        xe.Attributes["value"].InnerText = strKeyValue;
                        XMLWebSetting.Save(System.Web.HttpContext.Current.Server.MapPath("~/" + strWhich + ""));
                        break;
                    }
                }
            }
            catch (System.Exception Ex) {
                throw Ex;
            }
        }
        #endregion

        #region 读取 XML中指定节点值
        public static string GetConfig(string strKeyName) {
            return GetConfig(strKeyName, "Web.config");
        }

        /// <summary>
        /// 读取 XML中指定节点值
        /// </summary>
        /// <param name="strKeyName">节点键名</param>
        /// <returns>指定节点键值</returns>
        public static string GetConfig(string strKeyName, string strWhich) {
            //创建XML文档实例
            System.Xml.XmlDocument XMLWebSetting = new System.Xml.XmlDocument();

            //打开XML文档
            XMLWebSetting.Load(System.Web.HttpContext.Current.Server.MapPath("~/" + strWhich + ""));

            //查找节点所在位置
            System.Xml.XmlNodeList XmlNodeList = XMLWebSetting.SelectSingleNode("//appSettings").ChildNodes;

            //查找指定节点
            string strKeyValue = "";
            foreach (System.Xml.XmlNode xn in XmlNodeList) {
                Regex reg = new Regex("<!--(.*?)");
                if (reg.IsMatch(xn.OuterXml) == false) {
                    System.Xml.XmlElement xe = (System.Xml.XmlElement)xn;
                    if (xe.Attributes["key"].InnerText == strKeyName) {
                        strKeyValue = xe.Attributes["value"].InnerText;
                        break;
                    }
                }
            }

            return strKeyValue;
        }
        #endregion
    }
}